package com.uiotsoft.small.app.entity;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.uiotsoft.small.config.APPConfig;
import com.uiotsoft.small.http.SmallHttp;
import com.uiotsoft.small.mqtt.MqttClientOld;
import com.uiotsoft.util.encrypt.MD5Utils;
import com.uiotsoft.util.encrypt.small.SignUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class BaseAppClient {
    protected String mobile;
    protected String si;
    protected String appSecret;
    protected String appKey;
    protected String token = null;
    protected String userUnique;
    protected String username;
    protected String password;
    protected String clientId;
    protected String mqttUrl;
    protected String gatewayUrl;
    protected String subTopic;
    protected SmallHttp smallHttp;
    protected String env;
    protected String sn;
    protected MqttClientOld myMqttClient;

    public BaseAppClient(String env, String mobile, String si, String sn){
        this.env = env;
        this.mobile = mobile;
        this.sn = sn;
        this.si = si;
        if (env.toLowerCase().startsWith("chk")) {
            this.appKey = APPConfig.CHK_appKey;
            this.appSecret = APPConfig.CHK_appSecret;
            gatewayUrl = APPConfig.CHK_GatewayUrl;
            mqttUrl = APPConfig.CHK_MqttUrl;
        } else if (env.toLowerCase().startsWith("release")) {
            this.appKey = APPConfig.Release_appKey;
            this.appSecret = APPConfig.Release_appSecret;
            gatewayUrl = APPConfig.Release_GatewayUrl;
            mqttUrl = APPConfig.Release_MqttUrl;
        }
        smallHttp = new SmallHttp(appKey, appSecret, gatewayUrl);
        if (si == null || si.equals("")){
            register();
        }
        clientId = "uiot_app-" + this.si;
        subTopic = "app/+/+/" + this.si + "/+";
        Long time = System.currentTimeMillis();
        if (token != null) {
            username = appKey + "|" + this.si + "|uiot_app|" + time + "|" + token;
        } else {
            username = appKey + "|" + this.si + "|uiot_app|" + time;
        }
        password = MD5Utils.MD5Encoding(username + appSecret, "");
    }

    public void register(){
        String method = "backdevice.si.register";
        String data = "{\"appDevice\":\"phone\",\"appImei\":\"1586951954.71262\",\"appMac\":\"F0:0F:EC:A7:E5:OP\",\"appModel\":\"Xiaomi:MI 6\",\"appPackage\":\"com.xxx\",\"appSys\":\"android\",\"appVer\":\"V5.01.001\",\"sysVer\":\"8.1.0\",\"resolvingPower\":\"1080*2340\"}";
        String result = smallHttp.requestPost(method,data,null);
        String si = JSONUtil.parseObj(result).getJSONObject("data").getStr("si");
        this.si = si;
    }

    /**
     * 验证码方式登录
     */
    public void appVerifyCodeLogin(){
        String method = "app.login.verifyCode";
        String data = "{\"appLanguage\":\"ZH_CN\",\"areaCode\":\"86\",\"username\":\"\",\"verifyCode\":\"000000\",\"si\":\"\",\"locations\":\"\",\"loginAddress\":\"\",\"oemFirm\":\"0X8001\",\"appModel\":\"android\"}";
        login(method,data);
    }

    /**
     * 验证码方式登录
     */
    public void appPasswordLogin(){
        String method = "app.login.password";
        String data = "{\"appLanguage\":\"ZH_CN\",\"areaCode\":\"86\",\"username\":\"\",\"password\":\"abc123\",\"si\":\"\",\"locations\":\"\",\"loginAddress\":\"\",\"oemFirm\":\"0X8001\",\"appModel\":\"android\"}";
        login(method,data);
    }

    public void login(String method, String data){
        JSONObject dataJson = JSONUtil.parseObj(data);
        dataJson.put("username",mobile);
        dataJson.put("si",si);
        String result = smallHttp.requestPost(method,dataJson.toString(),null);
        JSONObject respDataJson = JSONUtil.parseObj(result).getJSONObject("data");
        String userUnique = respDataJson.getStr("userUnique");
        String token = respDataJson.getStr("token");
        this.userUnique = userUnique;
        this.token = token;
    }

    /**
     * 生成遗嘱消息
     * @return
     */
    public byte[] getWillData() {
        String lanAppOffLine = "{\"appVersion\":\"V5.00.001\",\"appSys\":\"android8.1.0\",\"userUnique\":\"\",\"sn\":\"\",\"appOemFirm\":\"0X8001\",\"appLanguage\":\"ZH_CN\",\"netWorkConnectionType\":\"wifi\"}";
        JSONObject lineStateJson = JSONUtil.parseObj(lanAppOffLine);
        lineStateJson.put("sn", sn);
        if (env.toLowerCase().endsWith("local")) {
            lineStateJson.put("userUnique", "uiot");
        } else {
            lineStateJson.put("userUnique", userUnique);
        }
        String willMsg = getSendData(lineStateJson);
        log.debug("\n******遗嘱消息是……{}", willMsg);
        byte[] willMsgByte = SignUtil.getPublishMessage(willMsg,appKey, appSecret);
        return willMsgByte;
    }
    public String getSendData(JSONObject data){
        JSONObject sendData = new JSONObject();
        sendData.put("header",getHeader());
        sendData.put("payload",data);
        return sendData.toString();
    }
    public JSONObject getHeader(){
        String header = "{\"clientType\":\"uiot_app\",\"identity\":\"\",\"msgId\":\"\",\"appkey\":\"\",\"userUnique\":\"\",\"params\":{\"si\":\"\"},\"version\":\"1.0\",\"isEncrypt\":\"true\"}";
        JSONObject headerJson = JSONUtil.parseObj(header);
        headerJson.put("identity", si);
        headerJson.put("appkey", appKey);
        headerJson.put("userUnique", userUnique);
        JSONObject paramsJson = headerJson.getJSONObject("params");
        paramsJson.put("si",si);
        headerJson.put("params",paramsJson);
        long time = System.currentTimeMillis();
        headerJson.put("msgId",time+"");
        return headerJson;
    }

    public String getATCTopic(String model, String type){
        String tmp = "common/app/{}/{}/{}";
        return StrUtil.format(tmp,model,sn,type);
    }

    public String getATHTopic(String model, String type){
        String tmp = "host/app/{}/{}/{}";
        return StrUtil.format(tmp,model,sn,type);
    }

}
